package com.david.cloud.service.impl;

import com.david.cloud.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Date;

@Slf4j
@Service
@RefreshScope
public class MailSerciceImpl implements MailService {
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public boolean send(String email, String code) {
        send(new String[]{email}, "cloud notify", code);
        return true;
    }

    public void send(String[] to, String subject, String text) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(to);
            helper.setSentDate(new Date());
            helper.setSubject(subject);
            helper.setText(text);
            mailSender.send(mimeMessage);
            log.info("send mail to {} success", Arrays.toString(to));
        } catch (MessagingException e) {
            log.error("send mail error", e);
        }
    }


}
